package com.demo.redis.subpub;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.serializer.DefaultDeserializer;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

@Component
public class ConsumerObject implements MessageListener, InitializingBean {

    @Autowired
    StringRedisSerializer stringRedisSerializer;

    @Autowired
    GenericJackson2JsonRedisSerializer genericToStringSerializer;
    @Override
    public void onMessage(Message message, byte[] pattern) {
//        MessageBean messageBean = (MessageBean) genericToStringSerializer.deserialize(message.getBody());
        JdkSerializationRedisSerializer defaultDeserializer = new JdkSerializationRedisSerializer();
        MessageBean messageBean = (MessageBean) defaultDeserializer.deserialize(message.getBody());
        System.out.println(String.format("收到来自%s的消息：%s", stringRedisSerializer.deserialize(pattern),
                messageBean.toString()));
    }
    @Autowired
    RedisMessageListenerContainer container;
    @Override
    public void afterPropertiesSet() throws Exception {
        container.addMessageListener(this, ChannelTopic.of("chatMessage"));
    }
}
